#include "wifi_connection.h"
#include <Arduino.h>
#include <String.h>
#include <ESP8266WiFi.h>
#include <FS.h>

// 定义 默认的AP 信息
const char* apSSID = "ESP8266_Config_AP";
const char* apPassword = "12345678";
// 配置文件路径
const char* configFile = "/config.txt";
static wifi_cabllback * wc_cb;

static void callback_mode(const char * ssid, const char * password, const char * ip, int mode) {
  wifi_info wi;
  memcpy(wi.ssid, ssid, sizeof(wi.ssid));
  memcpy(wi.password, password, sizeof(wi.password));
  memcpy(wi.ip, ip, sizeof(wi.ip));
  if (wc_cb && wc_cb->wc_cb)
  {
    wc_cb->wm_cb(mode, &wi); // Notify connection status
  }
}

// 清除 Wi-Fi 配置
void clearWifiConfig() {
    // 断开当前的 Wi-Fi 连接
    WiFi.disconnect(true);
    WiFi.mode(WIFI_OFF);

    // 清除存储的 Wi-Fi 配置文件
    if (SPIFFS.begin()) {
        if (SPIFFS.exists(configFile)) {
            if (SPIFFS.remove(configFile)) {
                Serial.println("Wi-Fi 配置文件已删除");
            } else {
                Serial.println("删除 Wi-Fi 配置文件失败");
            }
        } else {
            Serial.println("Wi-Fi 配置文件不存在");
        }
    } else {
        Serial.println("SPIFFS 初始化失败");
    }

    // 重新进入 AP 模式
    WiFi.mode(WIFI_AP);
    WiFi.softAP(apSSID, apPassword);
    callback_mode(apSSID, apPassword, WiFi.softAPIP().toString().c_str(), 0);
}

// 读取存储的 Wi-Fi 配置
static void readWiFiConfig(String& wifiSSID, String& wifiPassword, const char* configFile) {
  if (SPIFFS.begin()) {
    if (SPIFFS.exists(configFile)) {
      File file = SPIFFS.open(configFile, "r");
      if (file) {
        wifiSSID = file.readStringUntil('\n');
        wifiSSID.trim();
        wifiPassword = file.readStringUntil('\n');
        wifiPassword.trim();
        file.close();
      }
    }
  }
}

// 保存 Wi-Fi 配置到文件
static void saveWiFiConfig(const String& wifiSSID, const String& wifiPassword, const char* configFile) {
  if (SPIFFS.begin()) {
    File file = SPIFFS.open(configFile, "w");
    if (file) {
      file.println(wifiSSID);
      file.println(wifiPassword);
      file.close();
    }
  }
}

void wifiConnect(const char * ssid, const char * password) {
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);

    int maxRetries = 20; // 最大重试次数
    int retryCount = 0;
    while (WiFi.status() != WL_CONNECTED && retryCount < maxRetries) {
      if (wc_cb && wc_cb->wc_cb) {
        wc_cb->wc_cb(0); // Notify connecting status
        retryCount++;
        delay(500);
      }
    }

    wifi_info wi;
    int wifi_mode = 0; // 0: AP, 1: STA

    if (WiFi.status() == WL_CONNECTED) {
      saveWiFiConfig(ssid, password, configFile);
      wifi_mode = 1;
      callback_mode(ssid, password, WiFi.localIP().toString().c_str(), wifi_mode);
    }

    if (wifi_mode == 0) {
      WiFi.mode(WIFI_AP);
      WiFi.softAP(apSSID, apPassword);
      callback_mode(apSSID, apPassword, WiFi.softAPIP().toString().c_str(), wifi_mode);
    }


}

void setupWiFiConnect(wifi_cabllback *_wc_cb) {
  wc_cb = _wc_cb;
  // 读取 Wi-Fi 配置
  String wifiSSID, wifiPassword;
  readWiFiConfig(wifiSSID, wifiPassword, configFile);

  wifi_info wi;
  if (wifiSSID.length() == 0 ) {
    WiFi.mode(WIFI_AP);
    WiFi.softAP(apSSID, apPassword);
    callback_mode(apSSID, apPassword, WiFi.softAPIP().toString().c_str(), 0);
    return;
  }
  wifiConnect(wifiSSID.c_str(), wifiPassword.c_str());
}

wifi_opt_t wifi_opt = {
    .setup = setupWiFiConnect,
    .connect = wifiConnect,
    .clear = clearWifiConfig
};